import { makeAutoObservable, runInAction } from 'mobx';
import { RootStore } from './index';
// import { apiRequest } from '../utils/apiRequest';

export interface Message {
  id: string;
  title: string;
  content: string;
  type: 'system' | 'notification' | 'maintenance';
  isRead: boolean;
  createdAt: string;
}

export class MessageStore {
  rootStore: RootStore;
  messages: Message[] = [];
  isLoading = false;
  error: string | null = null;

  constructor(rootStore: RootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this);
  }

  setMessages(messages: Message[]) {
    this.messages = messages;
  }

  addMessage(message: Message) {
    this.messages.unshift(message);
  }

  markAsRead(id: string) {
    const message = this.messages.find(m => m.id === id);
    if (message) {
      message.isRead = true;
    }
  }

  setLoading(loading: boolean) {
    this.isLoading = loading;
  }

  setError(error: string | null) {
    this.error = error;
  }

  async fetchMessages() {
    this.setLoading(true);
    this.setError(null);

    // try {
    //   const response = await apiRequest('/messages');
    //   if (response.success) {
    //     runInAction(() => {
    //       this.setMessages(response.data.messages);
    //     });
    //   } else {
    //     runInAction(() => {
    //       this.setError(response.message || '获取消息列表失败');
    //     });
    //   }
    // } catch (error) {
    //   runInAction(() => {
    //     this.setError('网络错误，请稍后重试');
    //   });
    // } finally {
    //   this.setLoading(false);
    // }
  }

  async markMessageAsRead(id: string) {
    // try {
    //   const response = await apiRequest(`/messages/${id}/read`, {
    //     method: 'PUT',
    //   });
    //   if (response.success) {
    //     runInAction(() => {
    //       this.markAsRead(id);
    //     });
    //     return { success: true };
    //   } else {
    //     return { success: false, message: response.message };
    //   }
    // } catch (error) {
    //   return { success: false, message: '网络错误' };
    // }
  }

  get unreadCount() {
    return this.messages.filter(m => !m.isRead).length;
  }

  get messagesByType() {
    const grouped = this.messages.reduce(
      (acc, message) => {
        if (!acc[message.type]) {
          acc[message.type] = [];
        }
        acc[message.type].push(message);
        return acc;
      },
      {} as Record<string, Message[]>
    );

    return Object.entries(grouped).map(([type, messages]) => ({
      type,
      messages,
      unreadCount: messages.filter(m => !m.isRead).length,
    }));
  }
}
